################################## 
############ Preamble ############ 
################################## 

# set language to English
Sys.setenv(LANG = "en")

# clean up
rm(list = ls())

# Set working directory: please set your own
#setwd("~/Dropbox/JOP third submission/JOP replication/")

# load necessary packages
library(tidyverse)
library(haven)

# Import dataset
data_whole_spain <- read.dta13("01_data/whole_spain.dta")

# Make plot
fig4 <- data_whole_spain %>%
  mutate(Election = ifelse(ep == 1, "European", "Local")) %>%
  mutate(ciutadella2 = ifelse(ciutadella == 1, "Ciutadella", "Rest of Spain")) %>%
  ggplot(aes(x = period, y = pp_voteshare, color = Election, linetype = Election)) +
  scale_color_manual(values = c("blue", "red")) +
  stat_summary(fun = mean, geom = "point", position = position_dodge(width = 0.05)) +
  stat_summary(fun = mean, geom = "line", position = position_dodge(width = 0.05)) +
  scale_x_continuous(limits = c(0.5, 3.2),
                     breaks = c(1, 2, 3), 
                     labels = c("2 elections before\n(2009-11)", "1 election before\n(2014-15)", "2019")) +
  scale_y_continuous(limits = c(0, 70)) +
  geom_vline(xintercept = 2.5, linetype = 2, color = "black") +
  theme_bw() +
  facet_wrap(~ciutadella2) +
  labs(y = " ", x = " ") +
  guides(color = guide_legend(override.aes = list(linetype = c("solid", "dashed"))),  
         linetype = guide_legend(override.aes = list(color = c("blue", "red")))) 
fig4

ggsave("04_plots/fig4.png", plot = fig4, width = 25, height = 15, units = "cm")